package com.sis.tool.controller;

import com.sis.tool.exception.FileHandleException;
import com.sis.tool.exception.RequestException;
import com.sis.tool.service.IFileConverterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@RestController("kettle")
@Slf4j
public class FileConverterController {

    @Autowired
    private IFileConverterService fileConverterService;

    @PostMapping(value = "/convert", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<byte[]> convertPdfToImages(@RequestParam("file") MultipartFile sourceFile, @RequestParam("sourceType") String sourceType, @RequestParam("targetType") String targetType, HttpServletResponse response) {

        try {
            byte[] resultFileBytes = new byte[1024];
            if (Objects.equals(sourceType, "pdf")) {
                resultFileBytes = fileConverterService.convertPdfToImage(sourceFile.getInputStream(), sourceType, targetType);
            } else if (Objects.equals(sourceType, "ofd")) {
                resultFileBytes = fileConverterService.convertOfdToImage(sourceFile.getInputStream(), sourceType, targetType);
            } else if (Objects.equals(sourceType, "tif") || Objects.equals(sourceType, "tiff")) {
                resultFileBytes = fileConverterService.convertTifToImage(sourceFile.getInputStream(), sourceType, targetType);
            } else {
                throw new RequestException("sourceType无效");
            }
            // 构建响应
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/zip"));
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"converted_images.zip\"");
            return ResponseEntity.ok().headers(headers).body(resultFileBytes);
        } catch (IOException e) {
            return ResponseEntity.badRequest().body("上传文件访问出错".getBytes());
        } catch (FileHandleException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body((e.getMessage()).getBytes());
        } catch (RequestException e) {
            return ResponseEntity.badRequest().body(e.getMessage().getBytes());
        }


    }


}
